#pragma once
#include <iostream>
#include <string>
#include <cassert>
#include <functional>
#include "Epoller.hpp"
#include "Sock.hpp"
#include "Log.hpp"
#include "Err.hpp"

const static uint16_t gport = 8888;
using  func_t = std::function<std::string(std::string)>;

class EpollServer
{
    const static int gnum = 64;

public:
    EpollServer(func_t func, uint16_t port = gport) : _func(func), _port(port)
    {
    }

    void InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        _epoller.Create();
        logMessage(Debug, "init server success");
    }

    void Start()
    {
        // 将_listensock添加到epoll当中
        bool r = _epoller.AddEvent(_listensock.Fd(), EPOLLIN);
        assert(r);
        (void)r;

        int timeout = -1;
        while (true)
        {
            int n = _epoller.Wait(_revs, gnum, timeout);
            switch (n)
            {
            case 0:
                logMessage(Debug, "timeout...");
                break;
            case -1:
                logMessage(Warning, "epoll_wait failed");
                break;
            default:
                logMessage(Debug, "有%d个事件就绪了", n);
                HandlerEvents(n);
                break;
            }
        }
    }

    void HandlerEvents(int num)
    {
        for (int i = 0; i < num; ++i)
        {
            int fd = _revs[i].data.fd;
            uint32_t events = _revs[i].events;
            logMessage(Debug, "正在处理%d上的%s", fd, (events & EPOLLIN) ? "EPOLLIN" : "OTHER");
            if (events & EPOLLIN)
            {
                if (fd == _listensock.Fd())
                {
                    // 新连接到来
                    // logMessage(Debug, "get a new link...");
                    std::string clientip;
                    uint16_t clientport;
                    int sock = _listensock.Accept(&clientip, &clientport);
                    if (sock < 0)
                    {
                        continue;
                    }
                    logMessage(Debug, "%s:%d 已经连上了服务器", clientip.c_str(), clientport);
                    bool r = _epoller.AddEvent(sock, EPOLLIN);
                    assert(r);
                    (void)r;
                }
                else
                {
                    // 读事件
                    char requset[1024];
                    ssize_t s = recv(fd, requset, sizeof(requset) - 1, 0);
                    if (s > 0)
                    {
                        requset[s -2] = '\0';
                        std::string response = _func(requset);
                        send(fd, response.c_str(), response.size(), 0);
                    }
                    else
                    {
                        if (s == 0)
                        {
                            logMessage(Info, "client quit...");
                        }
                        else
                        {
                            logMessage(Info, "recv error, client quit...");
                        }
                        // 因为epoll在操作fd的时候，fd必须是合法的，所以必须先在epoll里删除fd,然后再关闭fd
                        _epoller.DelEvent(fd);
                        close(fd);
                    }
                }
            }
        }
    }

    ~EpollServer()
    {
        _listensock.Close();
        _epoller.Close();
    }

private:
    uint16_t _port;
    Sock _listensock;
    Epoller _epoller;
    struct epoll_event _revs[gnum];
    func_t _func;
};